package Http;

import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import Shop.Item;

public class HttpInterface {
	
	private HttpWrapper handler;
	private String user;
	private String pw;
		
	public HttpInterface(String username, String password){
		 handler = new HttpWrapper();
		 user = username;
		 pw = password;		 
	}

	public boolean loggedIn(){
		String htmlCode = handler.httpPostPage("http://www.neopets.com/objects.phtml?type=inventory", "");
		Matcher matcher = Pattern.compile(user).matcher(htmlCode);
		if(matcher.find()){
			return true;
		}
		return false;
	}
	
	public int login(){
		String requestBody = "destination=&username=" + user + "&password=" + pw;
		handler.httpPostPage("http://www.neopets.com/login.phtml", requestBody);		
                String htmlCode = handler.httpPostPage("http://www.neopets.com/index.phtml", "");
                String userPattern = "<a href=\"/userlookup.phtml?user="+user+"\""+">"+user+"</a>";
                if (htmlCode.contains(userPattern)){		
			return 1;
		}	
		else
			return 0;		
	}
	
	public Vector<Item> getList(int shopId, int umbral) throws FileNotFoundException{
		Vector<Item> stock = new Vector<Item>();
		int actualPage=0;
                //Book 5
                //Stamp 31
                //Chco 27
                //Mpots83  - Shop 73
                //BrightPots 93 - Shop 83
                //Booktastic 37 - 70
		String url = "http://items.jellyneo.net/index.php?go=show_items&name=&name_type=partial&desc=&cat=31&specialcat=0&status=0&rarity=0&sortby=price&numitems=75&ncoff=1&start=";
		String htmlCode = handler.httpPostPage(url+actualPage,"");
		String pagesPattern = "Page <b>1</b> of <b>(.*?)</b>.*?<br>First Page ";
		Matcher matcher = Pattern.compile(pagesPattern).matcher(htmlCode);
		int numPages=0;
		if(matcher.find()){
			numPages = Integer.parseInt(matcher.group(1));
		}
		String itemPattern = "go=item&amp;showitem=.*?\"><img src=.*?alt=\"(.*?)\".*?</a><br><b>(.*?) NP</b></td>";		
		int price;
		String name;
		FileOutputStream list = new FileOutputStream ("Lists"+File.separator+shopId+".txt");	
		for(int i=1 ; i<=numPages ; i++){
			if(i!=1){
				htmlCode = handler.httpPostPage(url+actualPage,"");
			}
			matcher = Pattern.compile(itemPattern).matcher(htmlCode);
			while(matcher.find()){
				price = Integer.parseInt(matcher.group(2).replaceAll(",", ""));
				name = matcher.group(1);
				if( price >= umbral){
					new PrintStream(list).println(name+","+price);
					stock.add(0,new Item(0,0,name,price));
				}
			}
			actualPage += 75;
		}
		return stock;
	}
	
	public Vector<Item> refresh(int shopId){
		Vector<Item> stockList = new Vector<Item>();
		String stockPattern = "j_info_id=(.*?)&stock_id=(.*?)&.*?<B>(.*?)</B>.*?<BR>Cost: (.*?) NP<BR>";
		String url = "http://www.neopets.com/objects.phtml?type=shop&obj_type=" + shopId;
		String htmlCode = handler.httpPostPage(url,"");
		Matcher matcher = Pattern.compile(stockPattern).matcher(htmlCode);
		int info,stock,price;
		String name;
		while(matcher.find()){
			info = Integer.parseInt(matcher.group(1));
			stock = Integer.parseInt(matcher.group(2));
			price = Integer.parseInt(matcher.group(4).replaceAll(",", ""));
			name = matcher.group(3);
			Item nuevo = new Item(info,stock,name,price);
			stockList.add(nuevo);
		}		
		return stockList;
	}
		
	public String buyItem(Item toBuy){
		double a = System.currentTimeMillis();
		String result = "";
		Captcha c = new Captcha();
		String captchaPage = "http://www.neopets.com/haggle.phtml?obj_info_id="+toBuy.getInfoId()+"&stock_id="+toBuy.getStockId()+"&brr=1366";
		String htmlCode = handler.httpPostPage(captchaPage, "");
		String captchaPattern = "<input type=\"image\" src=\"(.*?)\" style=";
		Matcher matcher = Pattern.compile(captchaPattern).matcher(htmlCode);
		String captcha="";
		if(matcher.find()){
			captcha = "http://www.neopets.com" + matcher.group(1);
			BufferedImage img = handler.httpPostImage(captcha);
			c.getCoords(img);
			htmlCode = handler.httpPostPage("http://www.neopets.com/haggle.phtml", "current_offer="+toBuy.getPrice()+"&x="+c.getX()+"&y="+c.getY());
			if(htmlCode.contains("I accept your offer")){
				Toolkit.getDefaultToolkit().beep();
				result = toBuy.getName() + " Bought For:" + toBuy.getPrice() + " Took(ms): " + (System.currentTimeMillis()-a) + " Profit:" + toBuy.getEstProfit();
			}
			else if(htmlCode.contains("SOLD OUT")){
				result = toBuy.getName() + " SOLD OUT! " + " Took(ms): " + (System.currentTimeMillis()-a) + " (GH)" + " Profit:" + toBuy.getEstProfit();
							
			}
		}
		else{
			result = toBuy.getName() + " SOLD OUT! " + " Took(ms): " + (System.currentTimeMillis()-a)+ " (NH)" + " Profit:" + toBuy.getEstProfit();
					
			}
		return result;
	}
}
